<template>
    <view class="container">
        <u-top-tips ref="uTips"></u-top-tips>
        <u-modal v-model="modalShow" :content="modalContent"></u-modal>
        <!-- 导航栏 -->
        <view class="navbar">
            <u-navbar title-color="#fff" back-icon-color="#ffffff" :is-back="false" :background="background"
                :back-text-style="{color: '#fff'}" :title="roomInfo.room_name">
                <view class="back_icon" @click="backToRoomList">
                    <u-icon name="arrow-left" color="#fff" size="32"></u-icon>
                </view>
            </u-navbar>
        </view>
        <view>
            <view class="tips color_fff size_12 align_c" :class="{ 'show':ajax.loading }">{{ajax.loadText}}</view>
            <view class="box-1" id="list-box">
                <view class="talk-list">
                    <view v-for="(item,index) in msgList" :key="item.message_id" :id="`msg-${item.id}`">
                        <view class="item flex_col" :class="item.message.user.user_id == userInfo.user_id == 1 ? 'push':'pull' ">
                            <image :src="item.message.user.user_head" placeholder="/static/image/imgLoad.jpg" mode="aspectFill"
                                class="headImg"></image>
                            <view class="userName" v-if="item.message.user.user_id !== userInfo.user_id">{{urldecode(item.message.user.user_name)}}</view>
                            <view class="content" v-if="item.message.type === 'text'">{{urldecode(item.message.content)}}</view>
                            <view style="margin: 40rpx 20rpx 20rpx 20rpx;" v-if="item.message.type === 'img'">
                                <image :src="getStaticUrl(item.message.content)" placeholder="/static/image/imgLoad.jpg"
                                    mode="widthFix" class="pic" @click="fullViewImage(getStaticUrl(item.message.content))"></image>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
            <view class="box-2">
                <view class="flex_col">
                    <view class="flex_grow">
                        <input type="text" class="content" v-model="content" placeholder="请输入聊天内容" placeholder-style="color:#DDD;"
                            :cursor-spacing="6">
                    </view>
                    <button class="send" @click="sendMessage">发送</button>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
    export default {
        data() {
            return {
                background: {
                    'background-image': 'linear-gradient(45deg, rgb(28, 187, 180), rgb(28, 205 ,158))'
                },
                roomInfo: '',
                userInfo: '',
                msgList: [],
                talkList: [],
                roomId: '',
                timeout: 30000, // 30s
                timeoutObj: null,
                nowTime: '',
                modalShow: false,
                modalContent: "",
                pageFrom: '',
                ajax: {
                    rows: 30, //每页数量
                    page: 1, //页码
                    flag: true, // 请求开关
                    loading: true, // 加载中
                    loadText: '正在获取消息'
                },
                content: ''
            }
        },
        mounted() {
            this.$nextTick(() => {

            });
        },
        onLoad(option) {
            let that = this;
            that.pageFrom = option.from
            that.roomId = option.id
            that.userInfo = uni.getStorageSync('userInfo');
            that.getRoomInfo();
            that.getMessageList();
            that.checkSocket();
            that.goToBottom()
        },
        onUnload() {
            uni.closeSocket()
            clearInterval(this.timeoutObj)
            console.log(this.nowTime + " WebSocket已断开，定时器已清除")
        },
        onPageScroll(e) {
            if (e.scrollTop < 5) {
                console.log('接触顶部')
                // this.getHistoryMsg();
            }
        },
        methods: {
            // 返回
            backToRoomList() {
                if (this.pageFrom === 'center') {
                    uni.switchTab({
                        url: '/pages/user/center'
                    })
                    return
                }
                uni.switchTab({
                    url: '/pages/room/roomList'
                })
            },
            // 解码
            urldecode(str) {
                return decodeURIComponent(decodeURIComponent(str))
            },
            // 判断回传的Url是否需要拼接
            getStaticUrl(url) {
                if (url.indexOf('https://') > -1 || url.indexOf('http://') > -1) {
                    return url;
                } else {
                    return 'https://api.bbbug.com/uploads/' + url;
                }
            },
            // 点击图片放大
            fullViewImage(url) {
                uni.previewImage({
                    urls: [url],
                    longPressActions: {
                        itemList: ['保存图片', '举报图片'],
                        success: function(data) {},
                        fail: function(err) {}
                    }
                });
            },
            // 获取当前时间
            getNowTime() {
                var that = this;
                let yy = new Date().getFullYear();
                let mm = new Date().getMonth() + 1;
                let dd = new Date().getDate();
                let hh = new Date().getHours();
                let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes();
                let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds();
                that.nowTime = yy + '-' + mm + '-' + dd + ' ' + hh + ':' + mf + ':' + ss;
            },
            // 检测心跳reset
            reset() {
                clearInterval(this.timeoutObj);
                this.start(); // 启动心跳
            },
            // 启动心跳 start 
            start() {
                let that = this;
                this.timeoutObj = setInterval(function() {
                    uni.sendSocketMessage({
                        data: 'heartBeat',
                        success: (res) => {
                            that.getNowTime();
                            console.log(that.nowTime + "心跳发送成功")
                        },
                        fail: (err) => {
                            that.getNowTime();
                            console.log(that.nowTime + "心跳发送失败正在重连")
                            that.getWebsocket();
                        }
                    });
                }, that.timeout);
            },
            // 获取房间信息
            async getRoomInfo() {
                const res = await this.$u.api.getRoomInfo({
                    "room_id": this.roomId,
                    "room_password": null
                })
                if (res.code !== 200) {
                    console.log(res)
                }
                this.roomInfo = res.data
                console.log(this.roomInfo)
            },
            // 获取历史消息
            async getMessageList() {
                var that = this;
                const res = await this.$u.api.getMessageList({
                    "room_id": this.roomId,
                    "page": 1,
                    "per_page": 5
                })
                if (res.code !== 200) {
                    console.log(res)
                    uni.setStorageSync('token', '');
                }
                console.log(res)
                this.historyMsg = JSON.parse(JSON.stringify(res.data))
                for (let i = 0, len = this.historyMsg.length; i < len; i++) {
                    that.msgList.unshift({
                        message: JSON.parse(this.historyMsg[i].message_content)
                    });
                }
                console.log(that.msgList)
            },
            // 判断是否已连接
            checkSocket() {
                let that = this;
                uni.sendSocketMessage({
                    data: 'heartBeat',
                    success: (res) => {
                        that.getNowTime();
                        console.log(that.nowTime + "连接检测成功")
                        return;
                    },
                    fail: (err) => {
                        // 心跳发送失败正在重连
                        that.getNowTime();
                        console.log(that.nowTime + "未检测到连接，正在重连")
                        that.getWebsocket();
                        uni.onSocketOpen(function(res) {
                            that.checkSocket()
                        });
                    }
                });
            },
            tips(title) {
                this.$refs.uTips.show({
                    title: decodeURIComponent(decodeURIComponent(title)),
                    type: 'success',
                    duration: '3000'
                })
            },
            async getWebsocket() {
                var that = this;
                const res = await this.$u.api.getWebsocket({
                    "channel": this.roomId
                })
                if (res.code !== 200) {
                    console.log(res)
                }
                console.log(res)
                // 确保已经关闭后再重新打开
                uni.closeSocket();
                uni.connectSocket({
                    url: "wss://websocket.bbbug.com/?account=" +
                        res.data.account + "&channel=" +
                        res.data.channel + "&ticket=" + res.data.ticket
                });
                uni.onSocketMessage(function(res) {
                    res = JSON.parse(res.data)
                    if (res.type == 'online') {
                        that.online = res
                    }
                    if (res.type == 'playSong') {
                        that.playSong = res
                    }
                    if (res.type == 'join') {
                        that.tips(res.content)
                    }
                    console.log(res)
                    if (res.type == 'text' || res.type == 'img') {
                        that.msgList.push({
                            message: res
                        });
                        if (res.user.user_id !== that.userInfo.user_id) {
                            if (res.type == 'img') {
                                that.tips(res.user.user_name + "说：[图文消息]")
                            } else {
                                that.tips(res.user.user_name + "说：" + res.content)
                            }
                        }
                    }
                    that.reset();
                });
            },
            // goToBottom
            goToBottom() {
                setTimeout(() => {
                    this.$nextTick(() => {
                        // 清空内容框中的内容
                        this.content = '';
                        uni.pageScrollTo({
                            scrollTop: 999999, // 设置一个超大值，以保证滚动条滚动到底部
                            duration: 0
                        });
                    })
                }, 200);
            },
            // 发送消息
            async sendMessage() {
                if (!this.content) {
                    uni.showToast({
                        title: '内容不能为空喔!',
                        icon: 'none'
                    })
                    return;
                }
                const res = await this.$u.api.sendMessage({
                    where: "channel",
                    to: this.roomId,
                    type: "text",
                    at: null,
                    msg: encodeURIComponent(this.content)
                })
                if (res.code === 200) {
                    this.content = ''
                    uni.pageScrollTo({
                        scrollTop: 999999, // 设置一个超大值，以保证滚动条滚动到底部
                        duration: 0
                    });
                    return;
                } else if (res.code === 401) {
                    uni.showToast({
                        title: res.msg,
                        icon: 'none'
                    })
                } else {
                    uni.showToast({
                        title: res.msg,
                        icon: 'none'
                    })
                }

            }
        }
    }
</script>
<style lang="scss">
    @import "../../lib/global.scss";

    page {
        background-color: #F3F3F3;
        font-size: 28rpx;
    }

    /* 加载数据提示 */
    .tips {
        position: fixed;
        left: 0;
        top: var(--window-top);
        width: 100%;
        z-index: 9;
        background-color: rgba(0, 0, 0, 0.15);
        height: 72rpx;
        line-height: 72rpx;
        transform: translateY(-80rpx);
        transition: transform 0.3s ease-in-out 0s;

        &.show {
            transform: translateY(0);
        }
    }

    .box-1 {
        width: 100%;
        height: auto;
        padding-bottom: 100rpx;
        box-sizing: content-box;

        /* 兼容iPhone全面屏 */
        margin-bottom: 0;
        margin-bottom: constant(safe-area-inset-bottom);
        margin-bottom: env(safe-area-inset-bottom);
    }

    .userName {
        position: absolute;
        margin-left: 105rpx;
        color: #606266;
    }

    .box-2 {
        position: fixed;
        left: 0;
        width: 100%;
        bottom: 0;
        height: auto;
        z-index: 2;
        border-top: #e5e5e5 solid 1px;
        box-sizing: content-box;
        background-color: #F3F3F3;

        /* 兼容iPhoneX */
        padding-bottom: 0;
        padding-bottom: constant(safe-area-inset-bottom);
        padding-bottom: env(safe-area-inset-bottom);

        >view {
            padding: 0 20rpx;
            height: 100rpx;
        }

        .content {
            background-color: #fff;
            height: 64rpx;
            padding: 0 20rpx;
            border-radius: 32rpx;
            font-size: 28rpx;
        }

        .imgContent {
            background-color: #fff;
            height: 64rpx;
            padding: 0 20rpx;
            border-radius: 32rpx;
            font-size: 28rpx;
        }

        .send {
            background-color: #42b983;
            color: #fff;
            height: 64rpx;
            margin-left: 20rpx;
            border-radius: 32rpx;
            padding: 0;
            width: 120rpx;
            line-height: 62rpx;

            &:active {
                background-color: #5fc496;
            }
        }
    }

    .talk-list {
        padding-bottom: 20rpx;

        /* 消息项，基础类 */
        .item {
            padding: 20rpx 20rpx 0 20rpx;
            align-items: flex-start;
            align-content: flex-start;
            color: #333;

            .headImg {
                width: 92rpx;
                height: 92rpx;
                border-radius: 50%;
                border: #fff solid 1px;
            }

            .pic {
                width: 200rpx;
                height: 200rpx;
            }

            .content {
                padding: 15rpx;
                border-radius: 4px;
                max-width: 500rpx;
                word-break: break-all;
                line-height: 52rpx;
                position: relative;
            }

            /* 收到的消息 */
            &.pull {
                .content {
                    margin-left: 20rpx;
                    background-color: #fff;
                    margin-top: 50rpx;

                    &::after {
                        content: '';
                        display: block;
                        width: 0;
                        height: 0;
                        border-top: 16rpx solid transparent;
                        border-bottom: 20rpx solid transparent;
                        border-right: 20rpx solid #fff;
                        position: absolute;
                        top: 10rpx;
                        left: -18rpx;
                    }
                }
            }

            /* 发出的消息 */
            &.push {
                /* 主轴为水平方向，起点在右端。使不修改DOM结构，也能改变元素排列顺序 */
                flex-direction: row-reverse;

                .content {
                    margin-right: 32rpx;
                    background-color: #a0e959;

                    &::after {
                        content: '';
                        display: block;
                        width: 0;
                        height: 0;
                        border-top: 16rpx solid transparent;
                        border-bottom: 16rpx solid transparent;
                        border-left: 20rpx solid #a0e959;
                        position: absolute;
                        top: 30rpx;
                        right: -18rpx;
                    }
                }
            }
        }
    }
</style>
